package com.lwq.mall.seckill.controller;

import com.alibaba.fastjson.JSON;
import com.lwq.mall.seckill.dto.SeckillSkuRedisDto;
import com.lwq.mall.seckill.service.SeckillSkuService;
import com.msb.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * CrossOrigin处理跨域问题
 */
@Controller
@CrossOrigin
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    SeckillSkuService seckillSkuService;

    @GetMapping("/getSeckillSkus")
    public R getCurrentSeckillSessionSkus(){
        List<SeckillSkuRedisDto> currentSeckillSkus = seckillSkuService.getCurrentSeckillSkus();
        return R.ok().put("data", JSON.toJSONString(currentSeckillSkus));
    }


    @ResponseBody
    @GetMapping("/getSeckillSessionBySkuId")
    public R getSeckillSessionBySkuId(@RequestParam("skuId")Long skuId ){
        SeckillSkuRedisDto seckillSkuRedisDto = seckillSkuService.getSeckillSessionBySkuId(skuId);
        return R.ok().put("data", JSON.toJSONString(seckillSkuRedisDto));
    }


    /**
     * 秒杀抢购
     * @param killId
     * @param code
     * @param num
     * @return
     */
    @GetMapping("/kill")
    public String seckill(@RequestParam("killId")String killId,
                          @RequestParam("code")String code,
                          @RequestParam("num") int num, Model model){
        //1、校验登录 --->通过拦截器实现
       String orderSn = seckillSkuService.seckill(killId,code,num);
        model.addAttribute("orderSn",orderSn);
        return "success";
    }

}
